import React, { useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import type { UploadProps } from 'antd';
import { request } from "../../common/request";
import { urls } from "../../common/urls";
import './index.less';

const UploadImg = (prop: any) => {
  const {getAvatar} = prop; 
  const [groupImg, setGroupImg] = useState('');

  const handleUpload = (file: any) => {
    request({
        method: "post",
        data: {
          method: urls.uploadImg,
          file
        },
      }).then((res: any) => {
          const {url} = res.data;
            getAvatar(url);
            setGroupImg(url);
      });
  };

  useEffect(() => {
    setGroupImg(prop.groupImg);
  }, [prop.groupImg])

  const props: UploadProps = {
    showUploadList: false,
    beforeUpload: (file) => {
        handleUpload(file);
      return false;
    },
  };

  return (
    <>
      <Upload {...props} >
          {
              groupImg 
                ? <img
                    src={groupImg} 
                    className={`upload-img ${prop.className}`}
                    alt="avatar"
                /> 
                : <PlusOutlined/>
          }
      </Upload>
    </>
  );
};

export default UploadImg;